package cn.loveq.android.widget;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import cn.loveq.android.Constants;
import cn.loveq.android.R;
import cn.loveq.android.model.Comment;
import cn.loveq.android.util.ILoadDataResponse;
import cn.loveq.android.util.InformationDataLoader;

/**
 * 
 * 
 * 项目名称：loveq4Weibo 
 * 类名称：InteractiveGalleryViewItem 
 * 类描述：互动空间GalleryViewIetm
 * 创建人：李伟豪 创建时间：2011-12-5 下午04:50:39
 * 
 * @version
 * 
 */
public class InteractiveGalleryViewItem extends RelativeLayout {

	private static final int UPDATE_LISTVIEW = 1025;
	private static final int ERROR = 1026;
	private static final int UPDATE_FINISH = 1027;
	private static final int UPDATEING = 1028;
	private static final int RESERVED_SPACE = 5;
	private static final int MARK_HUGOO = 1;
	private static final int MARK_ZHI = 2;

	private final int current = 0;// 默认位置
	//private TextView textView;
	private RelativeLayout interactiveTop;
	private ListView hugoComments;// hugo的回复
	private ListView zhiComments;// 啊智的回复
	private int currentComments = -1;
	private LayoutInflater mInflater;
	private Context mContext;
	private View interactiveView;
	private LinearLayout HugoConvertView, ZhiConvertView;

	private final int color_red = Color.argb(100, 0, 0, 200);

	private boolean isRefreshFoot = false;// 判断是否可刷新
	private int pageIndex = 0;
	private int pageTotal = -1;
	private RelativeLayout loadingView;
	private RelativeLayout loadingMore;
	private View no_informationView;
	private InformationDataLoader dataLoader; // 数据读取器
	private boolean canLoad = false; // 是否能读取数据
	private List<Comment> infos = new ArrayList<Comment>(); // 数据集合
	private CommentAdapter hugoAdapter = null;
	private CommentAdapter zhiAdapter = null;
	LinearLayout loadingLayout;

	// 数据反馈
	private ILoadDataResponse dataResponse = new ILoadDataResponse() {

		// 获取数据成功时
		@Override
		public void onLoadDataComplete(ArrayList<Comment> nextInfo, int total, int current) {
			infos.addAll(nextInfo);
			pageIndex = current;
			pageTotal = total;
			Message msg = mHandler.obtainMessage();
			msg.what = UPDATE_LISTVIEW;
			msg.sendToTarget();
		}

		// 获取数据出错时
		@Override
		public void onLoadDataError(String errorMsg) {
			Message msg = mHandler.obtainMessage();
			msg.what = ERROR;
			msg.obj = errorMsg;
			canLoad = false;
			msg.sendToTarget();
		}

	};

	Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			ListView tempComments = getCurrentComments();
			CommentAdapter tempAdapter = getCurrentAdapter();
			switch (msg.what) {
			case UPDATE_LISTVIEW:
				tempComments.removeFooterView(loadingView);
				tempAdapter.notifyDataSetChanged();
				break;
			case ERROR:
				Toast.makeText(mContext, (String) msg.obj, Toast.LENGTH_SHORT).show();
				tempComments.removeFooterView(loadingView);
				break;
			case UPDATEING:
				tempComments.removeFooterView(loadingMore);// 移除加载更多
				tempComments.addFooterView(loadingView);// 加载中
				tempAdapter.notifyDataSetChanged();
				break;
			case UPDATE_FINISH:
				tempAdapter.notifyDataSetChanged();
				break;
			}
			if (tempAdapter.mData.size() == 0) {
				Toast.makeText(mContext, "暂无数据", Toast.LENGTH_LONG).show();
				tempComments.addFooterView(no_informationView);
				tempComments.setAdapter(null);
			}
			tempAdapter = null;
			tempComments = null;
		}

	};

	public InteractiveGalleryViewItem(Context context, int position) {
		super(context);

		this.mContext = context;
		dataLoader = new InformationDataLoader(dataResponse);

		// main
		this.mInflater = LayoutInflater.from(context);

		// 加载item
		loadingView = (RelativeLayout) mInflater.inflate(R.xml.loading, null);
		no_informationView = mInflater.inflate(R.xml.no_information, null);
		loadingMore = (RelativeLayout) mInflater.inflate(R.xml.loadmore, null);
		loadingMore.setOnClickListener(loadMoreListener);
		// initLoading();

		//setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));
		/*textView = new TextView(context);
		textView.setTextSize(20);
		textView.setText("互动空间界面");
		textView.setGravity(Gravity.CENTER);
		textView.setId(Constants.InteractiveTitle);
		textView.setBackgroundColor(color_red);

		addView(textView, new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT));*/

		interactiveView = mInflater.inflate(R.layout.interactive_main_layout, null);
		interactiveView.setId(Constants.HugoConvertViewID);
		
		interactiveTop = (RelativeLayout) interactiveView.findViewById(R.id.interactive_top);
		
		TextView hugoName = (TextView) interactiveView.findViewById(R.id.btn_interactive_HugoName);
		hugoName.setText(R.string.hugo);

		TextView zhiName = (TextView) interactiveView.findViewById(R.id.btn_interactive_ZhiName);
		zhiName.setText(R.string.a_zhi);
	
		// layoutParams = new
		// RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
		// LayoutParams.WRAP_CONTENT);
		// layoutParams.addRule(RelativeLayout.BELOW, textView.getId());
		// interactiveView.setLayoutParams(layoutParams);
		
		hugoComments = (ListView) interactiveView.findViewById(R.id.hugoComments);
		hugoComments.setOnScrollListener(new MyScrollListener());
		//LinearLayout.LayoutParams hugoLp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		//hugoComments.setLayoutParams(hugoLp);
		
		
		zhiComments = (ListView) interactiveView.findViewById(R.id.zhiComments);

		// hugo
		HugoConvertView = (LinearLayout) interactiveView.findViewById(R.id.HugoConvertView);
		HugoConvertView.setOnClickListener(HugoBtnView);

		// 啊智
		ZhiConvertView = (LinearLayout) interactiveView.findViewById(R.id.ZhiConvertView);
		ZhiConvertView.setOnClickListener(ZhiBtnView);

		//updateData();
		addView(interactiveView,new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));

	}

	View.OnClickListener loadMoreListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			mHandler.sendEmptyMessage(UPDATEING);
			loadNext();
		}
	};

	/**
	 * 
	 * 第一次更新数据
	 */
	private void updateData() {
		canLoad = true;
		switch (currentComments) {
		case MARK_HUGOO: {
			if (hugoAdapter == null) {
				hugoAdapter = new CommentAdapter();
				for (int i = 0; i < 10; i++) {
					Comment com = new Comment();
					com.setCommentContent("评论 " + i);
					com.setCommenter("评论者 " + i);
					com.setCommentTime(i + "");
					hugoAdapter.addItem(com);
				}
				hugoComments.addFooterView(loadingMore);
			}
			hugoComments.setAdapter(hugoAdapter);
		}
			break;
		case MARK_ZHI: {
			if (zhiAdapter == null) {
				zhiAdapter = new CommentAdapter();
				for (int i = 0; i < 10; i++) {
					Comment com = new Comment();
					com.setCommentContent("评论 " + i);
					com.setCommenter("评论者 " + i);
					com.setCommentTime(i + "");
					zhiAdapter.addItem(com);
				}
				zhiComments.addFooterView(loadingMore);
			}
			zhiComments.setAdapter(zhiAdapter);
		}
			break;
		default:
			break;
		}
	}

	/**
	 * Hugo的布局按钮监听器
	 */
	private View.OnClickListener HugoBtnView = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			currentComments = MARK_HUGOO;
			inflaterHugoComment();
			hugoComments.setBackgroundResource(R.drawable.cm);
		}
	};

	/**
	 * 啊智的布局按钮监听器
	 */
	private View.OnClickListener ZhiBtnView = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			currentComments = MARK_ZHI;
			inflaterZhiComment();
			zhiComments.setBackgroundResource(R.drawable.cm);
		}
	};

	/**
	 * 
	 * 方法名:inflaterHugoComment 方法说明：填充hugoComments的listView 创建人：李伟豪
	 * 创建时间：2011-12-5
	 * 
	 * @param
	 * @return void
	 * @Exception
	 */
	private void inflaterHugoComment() {
		if (hugoComments.isShown()) {// 如果没有显示
			if (zhiComments.getCount() != 0) {
				zhiComments.setAdapter(null);
				//zhiComments.setVisibility(View.INVISIBLE);
				setHeightToZero(zhiComments);
			}
			//hugoComments.setVisibility(View.INVISIBLE);
			LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) hugoComments.getLayoutParams();
			//LinearLayout.LayoutParams linearParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
			linearParams.height = this.getHeight() - interactiveTop.getHeight() - HugoConvertView.getHeight() - ZhiConvertView.getHeight() - RESERVED_SPACE;
			//hugoComments.setLayoutParams(linearParams);
			updateData();
		}
	}

	/**
	 * 
	 * 方法名:inflaterHugoComment 方法说明：填充hugoComments的listView 创建人：李伟豪
	 * 创建时间：2011-12-5
	 * 
	 * @param
	 * @return void
	 * @Exception
	 */
	private void inflaterZhiComment() {
		if (zhiComments.isShown()) {// 如果显示
			if (hugoComments.getCount() != 0) {
				hugoComments.setAdapter(null);
				//hugoComments.setVisibility(View.INVISIBLE);
				setHeightToZero(hugoComments);
			}
			//zhiComments.setVisibility(View.VISIBLE);
			LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) zhiComments.getLayoutParams();
			linearParams.height = this.getHeight() - interactiveTop.getHeight() - HugoConvertView.getHeight() - ZhiConvertView.getHeight() - RESERVED_SPACE;
			updateData();
		}
	}

	private void setHeightToZero(ListView listview) {
		switch (currentComments) {
		case MARK_HUGOO:
			zhiComments.setBackgroundDrawable(null);
			break;
		case MARK_ZHI:
			hugoComments.setBackgroundDrawable(null);
			break;
		default:
			break;
		}
		LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) listview.getLayoutParams();
		linearParams.height = 0;
		listview.setLayoutParams(linearParams);
	}

	private CommentAdapter getCurrentAdapter() {
		switch (currentComments) {
		case MARK_HUGOO:
			return hugoAdapter;
		case MARK_ZHI:
			return zhiAdapter;
		default:
			break;
		}
		return null;
	}

	private ListView getCurrentComments() {
		switch (currentComments) {
		case MARK_HUGOO:
			return hugoComments;
		case MARK_ZHI:
			return zhiComments;
		default:
			break;
		}
		return null;
	}

	/**
	 * 
	 * 
	 * 项目名称：loveq4Weibo 类名称：MyScrollListener 类描述：ListView滑动监听 创建人：李伟豪
	 * 创建时间：2011-12-6 下午06:59:09 修改人：Administrator 修改时间：2011-12-6 下午06:59:09
	 * 修改备注：
	 * 
	 * @version
	 * 
	 */
	class MyScrollListener implements OnScrollListener {

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
			// if(pageIndex == 1 && visibleItemCount >= totalItemCount) {
			// return;
			// }
			// 当ListView的第一行id + ListView可见id = 共有条数
			if (firstVisibleItem + visibleItemCount == totalItemCount) {
				isRefreshFoot = true;
			} else {
				isRefreshFoot = true;
			}
		}

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && isRefreshFoot) {
				// mHandler.sendEmptyMessage(1);
				// loadNext();
			}
		}
	}

	/**
	 * 获取下一页数据
	 */
	private void loadNext() {

		new Thread() {
			public void run() {
				try {
					Log.v("thread", ".......");
					Thread.sleep(2000);
					// isRefreshFoot = true;
					CommentAdapter tempAdapter = getCurrentAdapter();
					if (tempAdapter.mData.size() < 20) {
						for (int i = 0; i < 10; i++) {
							Comment com = new Comment();
							com.setCommentContent("评论 " + i);
							com.setCommenter("评论者 " + i);
							com.setCommentTime(i + "");
							tempAdapter.addItem(com);
						}
						mHandler.sendEmptyMessage(UPDATE_LISTVIEW);
					} else {
						mHandler.sendEmptyMessage(UPDATE_FINISH);
					}

					Log.v("thread", "end");
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}.start();
	}

	class CommentAdapter extends BaseAdapter {

		private ArrayList<Comment> mData = new ArrayList<Comment>();
		private LayoutInflater mInflater;

		public CommentAdapter() {
			mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		public void addItem(Comment item) {
			mData.add(item);

		}

		@Override
		public int getCount() {
			return mData.size();
		}

		@Override
		public Comment getItem(int position) {
			return mData.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			CommentItemHolder holder = null;

			if (convertView == null) {// 判断convertView是否存在 否则动态生成新的View和Holder
				holder = new CommentItemHolder();
				convertView = mInflater.inflate(R.layout.comment_list_item, null);
				holder.avatar = (ImageView) convertView.findViewById(R.id.iv_avatar);
				holder.commenter = (TextView) convertView.findViewById(R.id.tv_commenter);
				holder.commentContent = (TextView) convertView.findViewById(R.id.tv_comment_content);
				holder.commentTime = (TextView) convertView.findViewById(R.id.tv_comment_time);
				holder.commentsComment = (TextView) convertView.findViewById(R.id.tv_commentes_commente);
				convertView.setTag(holder);
			} else {// 是则 提取其中的holder
				holder = (CommentItemHolder) convertView.getTag();
			}
			// 为holder加载数据
			holder.avatar.setImageResource(R.drawable.icon);
			holder.commenter.setText(mData.get(position).getCommenter());
			holder.commentContent.setText(mData.get(position).getCommentContent());
			holder.commentTime.setText(mData.get(position).getCommentTime());
			return convertView;
		}
	}

	public class CommentItemHolder {
		public ImageView avatar;
		public TextView commenter;
		public TextView commentContent;
		public TextView commentTime;
		public TextView commentsComment;
	}

}
